import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * ViewUsers
 * Shows a display of all the users along with actions to modify users
 *
 *
 *  Date           	Name            	Action
 *  --------------------------------------------------------------------------------------
 *	03/06/11		Bethany				Created Class
 *
 *
 *
 * @author bethanysumner
 * @version $Revision: 1.0 $
 */


public class ViewUsers extends JPanel{
	
	/**
	 * Field main.
	 */
	private MainWindow main;
	/**
	 * Field database.
	 */
	private Database database;
	
	/**
	 * Field txtName.
	 */
	private JTextField txtName;
	/**
	 * Field btnSearch.
	 */
	private JButton btnSearch;
	/**
	 * Field btnAdd.
	 */
	private JButton btnAdd;
	/**
	 * Field btnEdit.
	 */
	private JButton btnEdit;
	/**
	 * Field btnDelete.
	 */
	private JButton btnDelete;
	/**
	 * Field btnSuspend.
	 */
	private JButton btnSuspend;
	/**
	 * Field table.
	 */
	private JTable table;
	/**
	 * Field model.
	 */
	private DefaultTableModel model;
	/**
	 * Field btnClose.
	 */
	private JButton btnClose;
	/**
	 * Field buttonListener.
	 */
	private ButtonListener buttonListener;
	/**
	 * Field tableListener.
	 */
	private TableListener tableListener;

	
	/**
	 * ViewUser's constructor
	 * @param main Reference to the main window
	 * @param database Reference to the database
	 */
	public ViewUsers(MainWindow main, Database database) {
		
		this.main = main;
		this.database = database;
		
		createLayout();
		
		if(main.getUsertype() == 0){  //systemAdmin
			showAllUsers();
			main.showMessage("Enter a username to search for a specific user.");
		}else{
			showAllPatients();
			main.showMessage("Enter a patient's username to search for a specific patient.");
			btnAdd.setText("Add New Patient");
		}
		
	} //end ViewUsers()
	
	
	/**
	 * Lays out the GUI components on the panel
	 */
	private void createLayout(){
		
		setLayout(null);
		
		JLabel lblName = new JLabel("Username:");
		lblName.setBounds(289, 24, 104, 16);
		add(lblName);
		txtName = new JTextField();
		txtName.setBounds(365, 18, 254, 28);
		add(txtName);
		txtName.setColumns(10);
		
		// BUTTONS
		buttonListener = new ButtonListener();
		
		btnAdd = new JButton("Add New User");
		btnAdd.setBounds(307, 379, 169, 29);
		btnAdd.addActionListener(buttonListener);
		add(btnAdd);
		
		btnSearch = new JButton("Search");
		btnSearch.setBounds(622, 18, 117, 29);
		btnSearch.addActionListener(buttonListener);
		add(btnSearch);
		
		btnEdit = new JButton("Edit");
		btnEdit.setBounds(17, 379, 141, 29);
		btnEdit.addActionListener(buttonListener);
		add(btnEdit);
		
		btnDelete = new JButton("Delete");
		btnDelete.setBounds(162, 379, 141, 29);
		btnDelete.addActionListener(buttonListener);
		add(btnDelete);
		
		btnClose = new JButton("Close");
		btnClose.setBounds(598, 379, 141, 29);
		btnClose.addActionListener(buttonListener);
		add(btnClose);
		
	}
	
	/**
	 * Shows all of the users in the system on the table
	 */
	private void showAllUsers(){
		String[] columnNames = {"First Name", "Last Name", "Username", "Password", "Email", "Sex", "UserType", "Suspended"};
		String[][] data;
		try {
			data = database.getAllUsers();
			addTable(data, columnNames);
		} catch (SQLException e) {
			main.showError("Error Connecting with Database");
			e.printStackTrace();
		}
	}
	

	/**
	 * Shows all of the patients in the system on the table
	 */
	private void showAllPatients(){
		String[] columnNames = {"First Name", "Last Name", "Username", "Email", "Sex"};
		String[][] data;
		try {
			data = database.getAllPatients();
			addTable(data, columnNames);
		} catch (SQLException e) {
			main.showError("Error Connecting with Database");
			e.printStackTrace();
		}
	}
	
	/**
	 * Cretes the table with the given data and columnNames
	 * @param data Data to populate the table
	 * @param columnNames Column Names
	 */
	private void addTable(String[][] data, String[] columnNames){
		
		model = new DefaultTableModel(data, columnNames);
		table = new JTable(model);
		tableListener = new TableListener();
		model.addTableModelListener(tableListener);
		
		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setBounds(20, 60, 720, 300);
		add(scrollPane);
		
	}
	
	/**
	 * Searches for a user given their name
	 * @param name The name of the user to search for
	 */
	private void search(String name){
		try {
			final ArrayList<String> s = database.viewUser(name);
			if(!s.isEmpty()){
				while(model.getRowCount() > 0){
					model.removeRow(0);
				}
				
				String[] userData = new String[2]; //doesn't matter what size toArray() will enlarge it for you
				userData = s.toArray(userData);
				model.addRow(userData);
				
			}else{
				main.showError("User not found");
			}
		} catch (SQLException e) {
			main.showError("User not found");
			e.printStackTrace();
		}
	}
	
	/**
	 * Brings up the add user panel
	 */
	private void addUser(){
		main.addTab("Add New User", new AddEditUser(main, database));
	}
	
	/**
	 * Brings up the edit user panel
	 */
	private void editUser(){
		if(table.getSelectedRow() >= 0){
			final String selectedUser = table.getValueAt(table.getSelectedRow(), 2).toString();
			main.addTab("Edit: " + selectedUser, new AddEditUser(main, database, selectedUser));
		}else{
			main.showError("Please select a user to edit");
		}
		
	}
	
	/**
	 * Deletes the selected user from the system
	
	 */
	private void deleteUser(){
		if(table.getSelectedRow() > 0){
			final String selectedUser = table.getValueAt(table.getSelectedRow(), 2).toString();
			try {
				database.deleteUser(selectedUser);
				model.removeRow(table.getSelectedRow());
				main.showAffirmation(selectedUser + " has been deleted");
			} catch (SQLException e) {
				main.showError("Error deleting User");
				e.printStackTrace();
			}
		}else{
			main.showError("Please select a user to delete");
		}
	}
	
	/**
	 * Closes the panel
	 */
	private void close(){
		main.removeTab(this);
		main.clearMessage();
	}
	
	
	
	
	
	/**
	 * ButtonListener
	 * ActionListener to listen when button has been pressed
	 *
	 *
	 *  Date           	Name            	Action
	 *  --------------------------------------------------------------------------------------
	 *	03/06/11		Bethany				Created Class
	 *
	 *
	 *
	 * @author bethanysumner
	 */
	private class ButtonListener implements ActionListener{
		
		/**
		 * Performs tasks corresponding to the action
		 * @param event The action event
		 * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
		 */
		public void actionPerformed(ActionEvent event){
			
			if(event.getSource().equals(btnSearch)){
				if(!txtName.getText().equals("")){
					search(txtName.getText());
				}else{
					main.showError("Please enter a username before searching");
				}
			}else if(event.getSource().equals(btnAdd)){
				addUser();
			}else if(event.getSource().equals(btnEdit)){
				editUser();
			}else if(event.getSource().equals(btnDelete)){
				deleteUser();
			}else if(event.getSource().equals(btnClose)){
				close();
			}
			
		}
		
	}// end ButtonListener
	
	/**
	 * @author Zachary
	 * Listener to see if table values are changed
	 */
	private class TableListener implements TableModelListener{

		/**
		 * Method tableChanged.
		 * @param e TableModelEvent
		 * @see javax.swing.event.TableModelListener#tableChanged(TableModelEvent)
		 */
		public void tableChanged(TableModelEvent e) {
			try {
				final int user = 2, first = 0, last = 1, password = 3, email = 4, sex = 5, type = 6, suspended = 7;
				if(e.getType() == 0){
					database.updateUser(
						model.getValueAt(e.getLastRow(),user).toString(), 
						model.getValueAt(e.getLastRow(),first).toString(), 
						model.getValueAt(e.getLastRow(),last).toString(), 
						model.getValueAt(e.getLastRow(),password).toString(), 
						model.getValueAt(e.getLastRow(),email).toString(),
						model.getValueAt(e.getLastRow(),sex).toString(),
						model.getValueAt(e.getLastRow(),type).toString(),
						Integer.parseInt(model.getValueAt(e.getLastRow(),suspended).toString())
					);
				}
					
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			
			
		}
		
	}
}
